/**
 * 微信公众平台开发模式(JAVA) SDK
 * (c) 2012-2013 ____′↘夏悸 <wmails@126.cn>, MIT Licensed
 * http://www.jeasyuicn.com/wechat
 */
package com.gson;

import com.gson.bean.EncryptInMessage;
import com.gson.util.Tools;
import com.gson.util.WCryptUtil;
import com.gson.util.XStreamFactory;
import com.gson.bean.WeixinAccount;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求拦截
 *
 * @author GodSon
 */
public class WeChatFilter implements Filter {

    private final Logger LOGGER = Logger.getLogger(WeChatFilter.class);
    private WCryptUtil cryptUti;

    @Override
    public void destroy() {
        LOGGER.info("WeChatFilter已经销毁");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        Boolean isGet = request.getMethod().equals("GET");

        if (isGet) {
            doGet(request, response);
        } else {
            doPost(request, response);
        }
    }

    private void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/xml");
        ServletInputStream in = request.getInputStream();
        String xmlMsg =  Tools.inputStream2String(in);
        LOGGER.info("收到微信信息："+xmlMsg);

        XStream xs = XStreamFactory.init(false);
        xs.ignoreUnknownElements();
        xs.alias("xml", EncryptInMessage.class);
        EncryptInMessage encryptInMessage = (EncryptInMessage) xs.fromXML(xmlMsg);
        String xml;
        if(StringUtils.isNotBlank(encryptInMessage.getEncrypt())){
            xmlMsg=cryptUti.decrypt(encryptInMessage.getEncrypt());
            LOGGER.info("解密收到微信信息："+xmlMsg);
            xml = WeChat.processing(xmlMsg,null);
//            xml=cryptUti.encrypt(xmlMsg);
            LOGGER.info("加密返回微信信息："+xml);
        }else{
            xml = WeChat.processing(xmlMsg,null);
        }

        response.getWriter().write(xml);
    }

    private void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = request.getServletPath();
        String pathInfo = path.substring(path.lastIndexOf("/"));
        String _token;
        String outPut = "error";
        if (pathInfo != null) {
            _token = pathInfo.substring(1);
            String signature = request.getParameter("signature");// 微信加密签名
            String timestamp = request.getParameter("timestamp");// 时间戳
            String nonce = request.getParameter("nonce");// 随机数
            String echostr = request.getParameter("echostr");//
            // 验证
            if (WeChat.checkSignature(_token, signature, timestamp, nonce)) {
                outPut = echostr;
            }
        }
        response.getWriter().write(outPut);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        WeixinAccount weixinAccount = WeixinAccount.getWeixinAccount();
        if(StringUtils.isNotBlank(weixinAccount.getEncodingAesKey())){
            cryptUti=new WCryptUtil(weixinAccount.getToken(),weixinAccount.getEncodingAesKey(),weixinAccount.getAppId());
        }
        LOGGER.info("WeChatFilter已经启动！");
    }

}
